package slave

import (
	"backend/internal/common/errorx"
	modbusTypes "backend/internal/core/types"
	"backend/internal/svc"
	"backend/internal/types"
	"context"
	"fmt"
	"net/http"

	"github.com/zeromicro/go-zero/core/logx"
)

type WriteRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWriteRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WriteRegisterLogic {
	return &WriteRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WriteRegisterLogic) WriteRegister(req *types.WriteRegister) (resp *types.WriteRegisterResponse, err error) {
	client := l.svcCtx.ClientManager.GetClient(req.DeviceName)
	if client == nil {
		errorStr := fmt.Sprintf("无法找到该设备: %s", req.DeviceName)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(http.StatusNotFound, errorStr)
	}
	logx.Debugf("写入寄存器: %+v", req)

	isSuccess, err := client.WriteRegister(uint8(req.SlaveId), modbusTypes.RegisterType(req.RegisterType),
		uint16(req.StartAddress), modbusTypes.ModbusFunctionCode(req.WriteFunc), req.DataType, req.ValueList)
	if err != nil {
		errorStr := fmt.Sprintf("写入设备: %v 寄存器失败: %v", req.DeviceName, err)
		logx.Errorf(errorStr)
		return nil, errorx.NewCodeError(404, errorStr)
	}

	return &types.WriteRegisterResponse{
		Status: http.StatusOK,
		Msg:    "写入寄存器成功",
		Data:   isSuccess,
	}, nil
}
